<template>
  <div class="p-2">
    <el-card v-if="props.userId" shadow="hover">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="商户" v-if="!props.userId" prop="clientId">
          <el-select v-model="queryParams.clientId" filterable clearable style="width: 240px">
            <el-option v-for="item in clientList" :label="item.userName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用ID" prop="appId">
          <el-input v-model="queryParams.appId" placeholder="请输入应用ID" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="密钥" prop="appSecret">
          <el-input v-model="queryParams.appSecret" placeholder="请输入密钥" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="轮询组名称" prop="groupName">
          <el-input v-model="queryParams.groupName" placeholder="请输入轮询组名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <template v-if="showSearch">
        <div v-if="!props.userId" :class="showSearch ? 'cusotm_search_show' : 'cusotm_search_hide'" class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
              <el-form-item label="商户" v-if="!isClient && !props.userId" prop="clientId">
                <el-select v-model="queryParams.clientId" filterable clearable style="width: 240px">
                  <el-option v-for="item in clientList" :label="item.userName" :value="item.userId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="应用ID" prop="appId">
                <el-input v-model="queryParams.appId" placeholder="请输入应用ID" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="密钥" prop="appSecret">
                <el-input v-model="queryParams.appSecret" placeholder="请输入密钥" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="轮询组名称" prop="groupName">
                <el-input v-model="queryParams.groupName" placeholder="请输入轮询组名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </template>
    </transition>

    <el-tooltip v-if="!props.userId" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button v-hasPermi="['system:PayApp:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </div>
          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="PayAppList" @selection-change="handleSelectionChange">
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            <el-tag type="success" v-if="row.status == 1">上线</el-tag>
            <el-tag type="info" v-else>下线</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商户" v-if="!isClient && !props.userId" align="center" prop="agentName">
          <template #default="{ row }">
            <div class="flex leading-[18px] flex-wrap flex-col items-center">
              <span v-if="isAdmin">{{ row.agentName }}</span>
              <el-icon v-if="isAdmin"><ArrowDown /></el-icon>
              <span class="cursor-pointer hover:text-[var(--el-color-primary)]" @click="copyText(row.clientName, '商户')">{{ row.clientName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="true" label="应用ID" align="center" prop="" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="cursor-pointer truncate hover:text-[var(--el-color-primary)]" @click="copyText(row.appId, '应用Id')">{{ row.appId }}</div>
          </template>
        </el-table-column>
        <el-table-column label="密钥" align="center" prop="appSecret" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="cursor-pointer truncate hover:text-[var(--el-color-primary)]" @click="copyText(row.appSecret, '密钥')">
              {{ row.appSecret }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="网关地址" align="center" prop="gateway" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="cursor-pointer truncate hover:text-[var(--el-color-primary)]" @click="copyText(row.gateway, '网关地址')">
              {{ row.gateway }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="轮询组" v-if="!isClient" align="center" prop="groupName" />
        <el-table-column v-hasPermi="['admin:order:take']" v-if="showEat" label="吃单比例" align="center" prop="ratio">
          <template #default="{ row }">
            <div>{{ Number(row.ratio) }}%</div>
          </template>
        </el-table-column>
        <el-table-column label="今日收款单数/金额" width="140" align="center">
          <template #default="{ row }">
            <div v-if="row.payChart" class="flex flex-col">
              <span>{{ row.payChart.count }} 单</span>
              <span>USD {{ row.payChart.money }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="商户总额度/剩余额度" width="200" align="center">
          <template #default="{ row }">
            <div v-if="row.totalLimit" class="flex flex-col">
              <span v-if="row.totalLimit == 0">不限制</span>
              <template v-else>
                <span>USD {{ row.totalLimit }}</span>
                <span>USD {{ row.limitMoney }}</span>
              </template>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="轮询组总额度/剩余额度" v-if="!isClient" width="200" align="center">
          <template #default="{ row }">
            <div v-if="row.payChart?.total == 0" class="flex flex-col">
              <span>不限制</span>
            </div>
            <div v-else-if="row.payChart" class="flex flex-col">
              <span>USD {{ row.payChart.total }}</span>
              <span>USD {{ row.payChart.limit }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- <el-table-column label="金额限制" align="center" prop="goodsType">
          <template #default="{ row }">
            <div v-html="row.pricePlugin"></div>
          </template>
        </el-table-column> -->

        <el-table-column label="商品类型" align="center" prop="goodsType">
          <template #default="{ row }">
            <dict-tag :options="product_type" :value="row.goodsType" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="190" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:PayApp:edit']" link type="primary" size="large" icon="Edit" @click="handleUpdate(scope.row)"
                >修改</el-button
              >
            </el-tooltip>
            <el-tooltip content="吃单" v-if="showEat" placement="top">
              <el-button v-hasPermi="['admin:order:take']" link type="primary" size="large" @click="changeRadio(scope.row)">
                <svg-icon icon-class="make_fare" style="width: 18px; height: 18px"></svg-icon>
                <span>吃单</span>
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:PayApp:remove']" link type="danger" size="large" icon="Delete" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </el-tooltip>

            <el-button link type="primary" size="large" icon="Edit" @click="handleUpdateRemark(scope.row)"> 修改备注 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>
    <!-- 添加或修改应用列对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1000px" append-to-body>
      <el-form ref="PayAppFormRef" class="dialogForm" :model="form" :rules="rules">
        <div class="grid grid-cols-3">
          <el-form-item label="商户" prop="clientId" v-if="!form.appId && !props.userId">
            <el-select v-model="form.clientId" style="width: 200px">
              <el-option v-for="item in clientList" :label="item.userName" :value="item.userId"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品类型" prop="goodsType">
            <el-select v-model="form.goodsType" style="width: 200px">
              <el-option v-for="dict in product_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item v-if="form.goodsType == '2'" label="是否传邮箱" prop="needMail">
            <el-switch v-model="form.needMail" :active-value="1" :inactive-value="0" />
          </el-form-item>

          <el-form-item label="轮询组" prop="groupId">
            <el-select v-model="form.groupId" clearable style="width: 200px">
              <el-option v-for="item in groupList" :label="item.groupName" :value="item.groupId"></el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="24小时IP成功次数" prop="successCount">
            <el-input-number v-model="form.successCount" placeholder="24小时IP成功次数" />
          </el-form-item>

          <el-form-item label="24小时IP失败次数" prop="failCount">
            <el-input-number v-model="form.failCount" placeholder="24小时IP失败次数" />
          </el-form-item> -->

          <el-form-item label="邮箱验证策略" prop="policyId">
            <el-select v-model="form.policyId" clearable style="width: 200px">
              <el-option v-for="item in payPolicyList" :label="item.name" :value="item.policyId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="限制额度" prop="showLimit">
            <el-switch v-model="form.showLimit"></el-switch>
          </el-form-item>

          <el-form-item label="总额度" prop="totalLimit" v-if="form.showLimit">
            <el-input-number v-model="form.totalLimit" style="width: 80%" :precision="2" placeholder="总额度" />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :value="1">上线</el-radio>
              <el-radio :value="0">下线</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="自动上线" v-if="form.showLimit">
            <el-radio-group v-model="form.refreshAutoUp">
              <el-switch v-model="form.refreshAutoUp" :active-value="1" :inactive-value="0"></el-switch>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="额度刷新时间" prop="refreshTime" v-if="form.showLimit">
            <el-time-select v-model="form.refreshTime" style="width: 100%" start="00:00" step="00:30" end="23:59" placeholder="请选择额度刷新时间" />
          </el-form-item>
        </div>
        <!-- <el-form-item label="强制修改价格">
          <el-switch v-model="form.priceForce" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item> -->
        <!-- <el-form-item label="价格插件">
          <div class="flex items-start gap-5">
            <el-input v-model="form.pricePlugin" type="textarea" />
            <span class="leading-[18px]"
              >自动修改订单价格(单位美元);格式0-15:9.99表示价格在0到15美元间自动修改为9.99美元，多个价格规则可换行添加。</span
            >
          </div>
        </el-form-item> -->
        <div class="w-[100%] flex items-start justify-between gap-10">
          <el-form-item label="备注" prop="remark" class="w-[100%]">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="radioVisible" title="更改吃单比例" width="500px" append-to-body>
      <el-form ref="PayAppFormRef" class="dialogForm" :model="form" :rules="rules">
        <el-form-item label="吃单比例" prop="ratio">
          <div>
            <el-select v-model="form.ratio" filterable style="width: 180px">
              <el-option label="0" :value="0"></el-option>
              <template v-for="num in 100">
                <el-option :label="num" :value="num"></el-option>
              </template>
            </el-select>
            <div class="text-red-500 text-[12px]">0 代表无效(不吃单)</div>
          </div>
        </el-form-item>
        <el-form-item label="吃单区间" prop="ratioMin">
          <div class="flex gap-3">
            <el-input-number type="number" v-model="form.ratioMin" />
            <span>——</span>
            <el-input-number type="number" :max="10000000" v-model="form.ratioMax" />
          </div>
        </el-form-item>
        <div class="grid grid-cols-2 w-[100%]">
          <el-form-item label="更新时间">
            <div>{{ form.ratioTime }}</div>
          </el-form-item>

          <el-form-item label="是否更新时间" prop="updateTime">
            <el-switch v-model="form.updateTime" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormRadio">确 定</el-button>
          <el-button @click="radioVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--备注-->
    <el-dialog v-model="bzVisible" title="设置备注" width="500px" append-to-body>
      <el-form ref="PayAppFormRef" class="dialogForm">
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormBz">确 定</el-button>
          <el-button @click="bzVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PayApp" lang="ts">
import { listPayGroup } from '@/api/pay/PayGroup';
import useUserStore from '@/store/modules/user';
import {
  listPayApp,
  getPayApp,
  delPayApp,
  addPayApp,
  updatePayApp,
  getCurrency,
  getClient,
  updatePayAppRatio,
  getPayCahrtApp,
  setRemark,
  getPayPolicy
} from '@/api/pay/PayApp';
import { PayAppVO, PayAppQuery, PayAppForm } from '@/api/pay/PayApp/types';
import { selecTypetList } from '@/api/pay/PayType/index';

import { copyTextToClipboard } from '@/directive/common/copyText';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_country, product_type, app_account_status } = toRefs<any>(proxy?.useDict('sys_country', 'product_type', 'app_account_status'));
const props = defineProps({
  userId: {
    type: String,
    default: ''
  },
  selectType: {
    type: String,
    default: ''
  }
});
const isClient = computed(() => {
  const { isClient } = useUserStore();
  return isClient;
});
const isAdmin = computed(() => {
  const { isAdmin } = useUserStore();
  return isAdmin;
});
const showEat = computed(() => {
  const { isFeign } = useUserStore();
  return !isClient.value && isFeign;
});
const PayAppList = ref<PayAppVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const PayAppFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PayAppForm = {
  appId: undefined,
  appSecret: undefined,
  gateway: undefined,
  successTotal: 0,
  totalLimit: 0,
  refreshTime: '00:00',
  maxMoney: 0,
  ratio: 0,
  refreshAutoUp: undefined,
  deductStatus: 0,
  blackCountry: undefined,
  isForce: undefined,
  forceCurrency: '',
  needMail: 0,
  failCount: 0,
  successCount: 0,
  status: 1,
  remark: undefined,
  goodsType: 1
};
const data = reactive<PageData<PayAppForm, PayAppQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    appSecret: undefined,
    gateway: undefined,
    goodsType: undefined,
    successTotal: undefined,
    totalLimit: undefined,
    refreshTime: undefined,
    maxMoney: undefined,
    ratio: undefined,
    refreshAutoUp: undefined,
    deductStatus: undefined,
    blackCountry: undefined,
    isForce: undefined,
    forceCurrency: undefined,
    needMail: undefined,
    failCount: undefined,
    successCount: undefined,
    status: undefined,
    clientId: undefined,
    agentId: undefined,
    params: {}
  },
  rules: {
    goodsType: [{ required: true, message: '商品类型不能为空', trigger: 'change' }],
    totalLimit: [{ required: true, message: '总额度不能为空', trigger: 'blur' }],
    refreshTime: [{ required: true, message: '额度刷新时间不能为空', trigger: 'blur' }],
    maxMoney: [{ required: true, message: '单笔订单金额限制不能为空', trigger: 'blur' }],
    ratio: [{ required: true, message: '吃单比例不能为空', trigger: 'blur' }],
    refreshAutoUp: [{ required: true, message: '自动上线不能为空', trigger: 'blur' }],
    deductStatus: [{ required: true, message: '随机扣减不能为空', trigger: 'change' }],
    blackCountry: [{ required: true, message: '黑名单国家不能为空', trigger: 'blur' }],
    isForce: [{ required: true, message: '是否强制货币不能为空', trigger: 'blur' }],
    forceCurrency: [{ required: true, message: '强制货币类型不能为空', trigger: 'blur' }],
    needMail: [{ required: true, message: '是否传邮箱不能为空', trigger: 'blur' }],
    failCount: [{ required: true, message: '24小时失败次数不能为空', trigger: 'blur' }],
    successCount: [{ required: true, message: '24小时成功次数不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    clientId: [{ required: true, message: '商户不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询应用列列表 */
const getList = async () => {
  loading.value = true;
  if (props.selectType == '1') {
    queryParams.value.clientId = props.userId;
  }
  const res = await listPayApp(queryParams.value);
  PayAppList.value = res.rows.map((item) => {
    item.totalLimit = item.totalLimit ? item.totalLimit : '0.00';
    item.successTotal = item.successTotal ? item.successTotal : '0.00';
    item.limitMoney = parseFloat((Number(item.totalLimit) * 100 - Number(item.successTotal) * 100) / 100).toFixed(2);
    item.pricePlugin = item?.pricePlugin?.replace(/\n/g, '<br>');
    return item;
  });
  total.value = res.total;
  if (res.total > 0) {
    getPayChartList();
  } else {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  PayAppFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PayAppVO[]) => {
  ids.value = selection.map((item) => item.appName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  await getGroupList();
  dialog.visible = true;
  dialog.title = '添加应用';
  getPayPolicyList();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PayAppVO) => {
  reset();
  await getGroupList();
  const _appId = row?.appId || ids.value[0];
  const res = await getPayApp(_appId);
  Object.assign(form.value, res.data);
  if (form.value.totalLimit == 0) {
    form.value.showLimit = false;
  } else {
    form.value.showLimit = true;
  }
  dialog.visible = true;
  dialog.title = '修改应用';
  getPayPolicyList();
};

// 校验并解析规则（支持小数）
function parsePriceRules(input) {
  const rules = input.split('\n').map((rule) => rule.trim());
  const validRules = [];
  const isTrue = false;
  for (const rule of rules) {
    const match = rule.match(/^(\d+(\.\d+)?)-(\d+(\.\d+)?):(\d+(\.\d{1,2})?)$/);
    if (match) {
      const min = parseFloat(match[1]);
      const max = parseFloat(match[3]);
      const price = parseFloat(match[5]);

      if (min < max) {
        validRules.push({ min, max, price });
      } else {
        console.error(`规则无效: ${rule} (最小值应小于最大值)`);
      }
    } else {
      console.error(`规则格式错误: ${rule}`);
    }
  }

  return validRules.length == rules.length;
}

/** 提交按钮 */
const blackCountry = ref([]);
const submitForm = () => {
  PayAppFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!form.value.showLimit) {
        form.value.totalLimit = 0;
        form.value.refreshAutoUp = 0;
      } else if (form.value.showLimit && form.value.totalLimit == 0) {
        ElMessage.error('请设置总额度!,总额度必须大于0');
        return;
      }
      form.value.blackCountry = blackCountry.value.join(',');
      if (form.value.pricePlugin) {
        if (!parsePriceRules(form.value.pricePlugin)) {
          ElMessage.error('价格插件格式错误！请检查后重新提交');
          return false;
        }
      }
      if (props.userId) {
        form.value.clientId = props.userId;
      }
      buttonLoading.value = true;
      if (form.value.appId) {
        await updatePayApp(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPayApp(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PayAppVO) => {
  const _appIds = row?.appId || ids.value;
  await proxy?.$modal.confirm('是否确认删除应用ID为 ' + _appIds + ' 的数据项？').finally(() => (loading.value = false));
  await delPayApp(_appIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/PayApp/export',
    {
      ...queryParams.value
    },
    `PayApp_${new Date().getTime()}.xlsx`
  );
};

//获取商户列表
const clientList = ref([]);
const getClientList = async () => {
  let res = await getClient({ roleKey: 'client' });
  clientList.value = res.data;
};

// 复制成功
const copyText = (str: string, msg: string) => {
  if (!str) return;
  let newStr = str + '';
  let res = copyTextToClipboard(newStr);
  if (res) {
    ElMessage.success(msg + '复制成功');
  }
};

// 吃单比例更新
const radioVisible = ref(false);
const changeRadio = (row) => {
  radioVisible.value = true;
  let obj = JSON.parse(JSON.stringify(row));
  form.value = obj;
  form.value.ratio = Number(form.value.ratio);
  form.value.updateTime = true;
};
const submitFormRadio = () => {
  PayAppFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!(form.value.ratioMax >= form.value.ratioMin)) {
        ElMessage.error('请填写正确的吃单区间');
        return false;
      }
      form.value.blackCountry = blackCountry.value.join(',');
      buttonLoading.value = true;
      let res = await updatePayAppRatio(form.value).finally((buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      radioVisible.value = false;
      await getList();
    }
  });
};

// 轮询组列表
const groupList = ref([]);
const getGroupList = async () => {
  if (!groupList.value.length) {
    let res = await listPayGroup();
    groupList.value = res.rows;
  }
};

/**
 * 备注--商户
 */
const bzVisible = ref(false);
const submitFormBz = () => {
  buttonLoading.value = true;
  setRemark({ appId: form.value.appId, remark: form.value.remark })
    .then((res) => {
      bzVisible.value = false;
      getList();
      buttonLoading.value = false;
      ElMessage.success('配置成功');
    })
    .finally(() => (buttonLoading.value = false));
};
const handleUpdateRemark = (row) => {
  Object.assign(form.value, row);
  bzVisible.value = true;
};

/**
 * 应用收款订单统计
 */
const getPayChartList = async () => {
  let ids = PayAppList.value.map((item) => item.appId);
  let res = await getPayCahrtApp(ids);
  PayAppList.value.map((item) => {
    item.payChart = res.data.find((item2) => item2.appId == item.appId);
    return item;
  });
  loading.value = false;
};

const payPolicyList = ref([]);
const getPayPolicyList = () => {
  getPayPolicy({ type: 1 }).then((res) => {
    payPolicyList.value = res.data;
  });
};

onMounted(() => {
  if (!props.selectType) {
    getList();
    getClientList();
  }
});

defineExpose({ handleAdd, getList });
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  width: fit-content;
}
</style>
